const mysql = require('mysql');

const conn = mysql.createConnection({
    host: 'localhost',
    port: '3306',
    user: 'root',
    password: 'root',
    database: 'cdsd',
});

function done(sql, callback, param) {
    const arr = [sql, (err, data) => {
        if (err) {
            console.error(err);
        } else {
            callback(data);
        }
    }];
    if (param) arr.splice(1, 0, param);
    conn.query(...arr);
}

// 增
function add(param, condition) {
    const sql = `insert into ${condition}`;
    return new Promise(resolve => {
        done(sql, data => {
            resolve(data);
        }, param)
    })
}
// 删
function del(condition,table = 'user') {
    const sql = `delete from ${table} where ${condition}`;
    return new Promise(resolve => {
        done(sql, data => {
            resolve(data);
        })
    })
}
// 改
function edit(param, condition,table = 'user') {
    const sql = `update ${table} set ${condition}`;
    return new Promise(resolve => {
        done(sql, data => {
            resolve(data);
        }, param)
    })
}
// 完整查询
function search(table = 'user') {
    const sql = `select * from ${table}`;
    return new Promise(resolve => {
        done(sql, data => {
            resolve(data);
        })
    })
}
// 条件查询
function searchBy(condition, table = 'user') {
    const sql = `select * from ${table} where ${condition}`;
    return new Promise(resolve => {
        done(sql, data => {
            resolve(data);
        })
    })
}

module.exports = {
    add,
    del,
    edit,
    search,
    searchBy,
}